package com.hsjk.szwj.module.pay.service;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hsjk.szwj.framework.common.exception.ServiceException;
import com.hsjk.szwj.framework.common.exception.enums.GlobalErrorCodeConstants;
import com.hsjk.szwj.module.pay.constant.RefundOrderConstant;
import com.hsjk.szwj.module.pay.dal.dataobject.order.RefundOrderDO;
import com.hsjk.szwj.module.pay.dal.mysql.IPayOrderMapper;
import com.hsjk.szwj.module.pay.dal.mysql.IRefundOrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Arrays;

/**
 * @author chenjiawei
 * @desc
 * @Date 2023/08/24 18:34
 **/
@Service
@Slf4j
public class RefundOrderService extends ServiceImpl<IRefundOrderMapper, RefundOrderDO> {
    @Resource
    private IPayOrderMapper payOrderMapper;

    /**
     * 查询商户订单
     **/
    public RefundOrderDO queryMchOrder(Long mchId, Long mchRefundId, Long refundOrderId) {

        if (ObjectUtil.isNotNull(refundOrderId)) {
            return getOne(new LambdaQueryWrapper<RefundOrderDO>()
                    .eq(RefundOrderDO::getMchId, mchId)
                    .eq(RefundOrderDO::getId, refundOrderId));
        } else if (ObjectUtil.isNotNull(mchRefundId)) {
            return getOne(new LambdaQueryWrapper<RefundOrderDO>()
                    .eq(RefundOrderDO::getMchId, mchId)
                    .eq(RefundOrderDO::getMchRefundId, mchRefundId));
        } else {
            return null;
        }
    }


    /**
     * 更新退款单状态  【退款单生成】 --》 【退款中】
     **/
    public boolean updateInit2Ing(Long refundOrderId, String channelOrderNo) {

        RefundOrderDO updateRecord = new RefundOrderDO();
        updateRecord.setState(RefundOrderConstant.STATE_ING);
        updateRecord.setChannelOrderNo(channelOrderNo);

        return update(updateRecord, new LambdaUpdateWrapper<RefundOrderDO>()
                .eq(RefundOrderDO::getId, refundOrderId)
                .eq(RefundOrderDO::getState, RefundOrderConstant.STATE_INIT));
    }

    /**
     * 更新退款单状态  【退款中】 --》 【退款成功】
     **/
    @Transactional
    public boolean updateIng2Success(Long refundOrderId, String channelOrderNo) {

        RefundOrderDO updateRecord = new RefundOrderDO();
        updateRecord.setState(RefundOrderConstant.STATE_SUCCESS);
        updateRecord.setChannelOrderNo(channelOrderNo);
        updateRecord.setSuccessTime(LocalDateTime.now());

        //1. 更新退款订单表数据
        if (!update(updateRecord, new LambdaUpdateWrapper<RefundOrderDO>()
                .eq(RefundOrderDO::getId, refundOrderId)
                .eq(RefundOrderDO::getState, RefundOrderConstant.STATE_ING))
        ) {
            return false;
        }

        //2. 更新订单表数据（更新退款次数,退款状态,如全额退款更新支付状态为已退款）
        RefundOrderDO refundOrder = getOne(new LambdaQueryWrapper<RefundOrderDO>()
                .select(RefundOrderDO::getPayOrderId, RefundOrderDO::getRefundAmount)
                .eq(RefundOrderDO::getId, refundOrderId));
        int updateCount = payOrderMapper.updateRefundAmountAndCount(refundOrder.getPayOrderId(),
                refundOrder.getRefundAmount());
        if (updateCount <= 0) {
            throw new ServiceException(GlobalErrorCodeConstants.BAD_REQUEST.getCode(),
                    "更新订单数据异常");
        }

        return true;
    }


    /**
     * 更新退款单状态  【退款中】 --》 【退款失败】
     **/
    @Transactional
    public boolean updateIng2Fail(Long refundOrderId,
                                  String channelOrderNo,
                                  String channelErrCode, String channelErrMsg) {

        RefundOrderDO updateRecord = new RefundOrderDO();
        updateRecord.setState(RefundOrderConstant.STATE_FAIL);
        updateRecord.setErrCode(channelErrCode);
        updateRecord.setErrMsg(channelErrMsg);
        updateRecord.setChannelOrderNo(channelOrderNo);

        return update(updateRecord, new LambdaUpdateWrapper<RefundOrderDO>()
                .eq(RefundOrderDO::getId, refundOrderId)
                .eq(RefundOrderDO::getState, RefundOrderConstant.STATE_ING));
    }


    /**
     * 更新退款单状态  【退款中】 --》 【退款成功/退款失败】
     **/
    @Transactional
    public boolean updateIng2SuccessOrFail(Long refundOrderId, Integer updateState,
                                           String channelOrderNo, String channelErrCode,
                                           String channelErrMsg) {

        if (updateState == RefundOrderConstant.STATE_ING) {
            return true;
        } else if (updateState == RefundOrderConstant.STATE_SUCCESS) {
            return updateIng2Success(refundOrderId, channelOrderNo);
        } else if (updateState == RefundOrderConstant.STATE_FAIL) {
            return updateIng2Fail(refundOrderId, channelOrderNo, channelErrCode, channelErrMsg);
        }
        return false;
    }


    /**
     * 更新退款单为 关闭状态
     **/
    public Integer updateOrderExpired() {

        RefundOrderDO refundOrder = new RefundOrderDO();
        refundOrder.setState(RefundOrderConstant.STATE_CLOSED);

        return baseMapper.update(refundOrder,
                new LambdaQueryWrapper<RefundOrderDO>()
                        .in(RefundOrderDO::getState,
                                Arrays.asList(RefundOrderConstant.STATE_INIT,
                                        RefundOrderConstant.STATE_ING))
                        .le(RefundOrderDO::getExpiredTime, LocalDateTime.now())
        );
    }


    public IPage<RefundOrderDO> pageList(IPage iPage,
                                         LambdaQueryWrapper<RefundOrderDO> wrapper,
                                         RefundOrderDO refundOrder, JSONObject paramJSON) {
        if (ObjectUtil.isNotNull(refundOrder.getId())) {
            wrapper.eq(RefundOrderDO::getId, refundOrder.getId());
        }
        if (ObjectUtil.isNotNull(refundOrder.getPayOrderId())) {
            wrapper.eq(RefundOrderDO::getPayOrderId, refundOrder.getPayOrderId());
        }
        if (StringUtils.isNotEmpty(refundOrder.getChannelPayOrderNo())) {
            wrapper.eq(RefundOrderDO::getChannelPayOrderNo, refundOrder.getChannelPayOrderNo());
        }
        if (ObjectUtil.isNotNull(refundOrder.getMchId())) {
            wrapper.eq(RefundOrderDO::getMchId, refundOrder.getMchId());
        }
        if (ObjectUtil.isNotNull(refundOrder.getIsvId())) {
            wrapper.eq(RefundOrderDO::getIsvId, refundOrder.getIsvId());
        }
        if (refundOrder.getMchType() != null) {
            wrapper.eq(RefundOrderDO::getMchType, refundOrder.getMchType());
        }
        if (ObjectUtil.isNotNull(refundOrder.getMchRefundId())) {
            wrapper.eq(RefundOrderDO::getMchRefundId, refundOrder.getMchRefundId());
        }
        if (refundOrder.getState() != null) {
            wrapper.eq(RefundOrderDO::getState, refundOrder.getState());
        }
        if (ObjectUtil.isNotNull(refundOrder.getAppId())) {
            wrapper.eq(RefundOrderDO::getAppId, refundOrder.getAppId());
        }
        if (paramJSON != null) {
            if (StringUtils.isNotEmpty(paramJSON.getStr("createdStart"))) {
                wrapper.ge(RefundOrderDO::getCreateTime, paramJSON.getStr("createdStart"));
            }
            if (StringUtils.isNotEmpty(paramJSON.getStr("createdEnd"))) {
                wrapper.le(RefundOrderDO::getCreateTime, paramJSON.getStr("createdEnd"));
            }
        }
        // 三合一订单
        if (paramJSON != null && StringUtils.isNotEmpty(paramJSON.getStr("unionOrderId"))) {
            wrapper.and(wr -> {
                wr.eq(RefundOrderDO::getPayOrderId, paramJSON.getStr("unionOrderId"))
                        .or().eq(RefundOrderDO::getId, paramJSON.getStr("unionOrderId"))
                        .or().eq(RefundOrderDO::getChannelPayOrderNo, paramJSON.getStr("unionOrderId"))
                        .or().eq(RefundOrderDO::getMchRefundId, paramJSON.getStr("unionOrderId"));
            });
        }
        wrapper.orderByDesc(RefundOrderDO::getCreateTime);

        return page(iPage, wrapper);
    }
}
